package com.banzhi.shop.adapter;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.activity.MainActivity;
import com.banzhi.shop.activity.ViewPagerActivity;
import com.banzhi.shop.entity.GoodsDetails.GoodsSucai_Data;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.BitmapUtils;
import com.banzhi.shop.utils.PermissionPageUtils;
import com.banzhi.shop.utils.ShareUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.view.SpacingTextView;
import com.squareup.picasso.Picasso;

import java.io.Serializable;
import java.util.List;

/**
 * Created by HT on 2017/5/10.
 */

public class SucaiAdapter extends BaseAdapter<GoodsSucai_Data> {
    private Context context;

    public SucaiAdapter(Context context, List<GoodsSucai_Data> data) {
        super(context, data);
        this.context = context;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final GoodsSucai_Data data = getData().get(position);
        viewHolder holder = null;
        LinearLayoutManager layoutManager = null;
        if (convertView == null) {
            holder = new viewHolder();
            convertView = getInflater().inflate(R.layout.item_sucai, null);
            holder.tvtitle = (SpacingTextView) convertView.findViewById(R.id.tv_title);
            holder.tvtitle.setLetterSpacing(1);
            holder.rvimage = (RecyclerView) convertView.findViewById(R.id.rv_image);
            holder.llbaochun = (LinearLayout) convertView.findViewById(R.id.ll_baocun);
            holder.llcopy = (LinearLayout) convertView.findViewById(R.id.ll_copy);
            holder.llshare = (LinearLayout) convertView.findViewById(R.id.ll_share);
            holder.ivimage = (ImageView) convertView.findViewById(R.id.iv_image);
            layoutManager = new LinearLayoutManager(getContext());
            layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            holder.rvimage.setLayoutManager(layoutManager);
            convertView.setTag(holder);
        }
        holder = (viewHolder) convertView.getTag();
        holder.tvtitle.setText(data.getDetail());
        if (ASUtils.isCanUse(data.getThumb())) {
            Picasso.with(getContext()).load(data.getThumb()).placeholder(R.mipmap.zhanweitu).into(holder.ivimage);
        }
        CommonAdapter<String> adapter = new CommonAdapter<String>(context, R.layout.item_sucai_recycleview, data.getThumb_url()) {
            @Override
            public void convert(ViewHolder holder, String s, int position) {
                holder.setImageURI(R.id.iv_image, s);
            }
        };
        holder.rvimage.setAdapter(adapter);
        adapter.setOnItemClickListener(new CommonAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getContext(), ViewPagerActivity.class);
                intent.putExtra("images", (Serializable) data.getThumb_url());
                intent.putExtra("position", position);
                getContext().startActivity(intent);

            }
        });

        holder.llbaochun.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                //  showPopupwindow(data.getThumb_url(), data.getThumb());
                //保存图片
                SavePictures();
            }



            private void SavePictures() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < data.getThumb_url().size(); i++) {
                            BitmapUtils.saveImageToGallery((Activity) getContext(), BitmapUtils.returnBitmap(data.getThumb_url().get(i)));
                        }
                        if (ASUtils.isCanUse(data.getThumb())) {
                            BitmapUtils.saveImageToGallery((Activity) getContext(), BitmapUtils.returnBitmap(data.getThumb()));
                        }
                    }
                }).start();
                int sum = data.getThumb_url().size() + 1;
                ToastUtils.makeToastLong("保存成功" + sum + "张");

            }
        });
        holder.llcopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareUtils.copyLianjie((Activity) getContext(), data.getDetail());
            }
        });
        if ("1".equals(MyApp.loginMessage.getString("isagent",""))) {
            holder.llshare.setVisibility(View.VISIBLE);
        }else {
            holder.llshare.setVisibility(View.INVISIBLE);
        }
        holder.llshare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareCallBack.sucarShare(data, position);
            }
        });
        return convertView;
    }

    class viewHolder {
        SpacingTextView tvtitle;
        RecyclerView rvimage;
        LinearLayout llbaochun;
        LinearLayout llcopy;
        LinearLayout llshare;
        ImageView ivimage;
    }

    /**
     * 点击删除提示下是不是确定保存到相册
     *
     * @param images
     */
    private void showPopupwindow(final List<String> images, final String thumb) {
        //设置contentView
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.popupwindow_baochun_image, null);

        int width = getContext().getResources().getDisplayMetrics().widthPixels;
        int height = getContext().getResources().getDisplayMetrics().heightPixels;

        final PopupWindow popWindow = new PopupWindow(contentView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        TextView tvcancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvtrue = (TextView) contentView.findViewById(R.id.tv_true);
        RelativeLayout rl = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        tvcancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        tvtrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(getContext(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        == PackageManager.PERMISSION_GRANTED) {
                    //拥有读写文件权限
                    //  Log.i(TAG,"拥有读写文件权限");
                    SavePictures();

                } else {
                    return;
                }

            }

            private void SavePictures() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < images.size(); i++) {
                            BitmapUtils.saveImageToGallery((Activity) getContext(), BitmapUtils.returnBitmap(images.get(i)));
                        }
                        if (ASUtils.isCanUse(thumb)) {
                            BitmapUtils.saveImageToGallery((Activity) getContext(), BitmapUtils.returnBitmap(thumb));
                        }
                    }
                }).start();
                popWindow.dismiss();
                //  ToastUtils.makeToastShort("保存图片成功.");
                ToastUtils.makeToastShort("保存成功" + images.size() + "张");
            }
        });
        popWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public interface ShareCallBack {
        void sucarShare(GoodsSucai_Data data, int position);

    }

    private ShareCallBack shareCallBack;

    public void setCallBack(ShareCallBack callBack) {
        this.shareCallBack = callBack;
    }
}